package com.wxlgroup.springboot.config;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wxlgroup.springboot.commons.Response;
import com.wxlgroup.springboot.entity.User;
import com.wxlgroup.springboot.exception.ServiceException;
import com.wxlgroup.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @auther:wxl
 * @Date:2022/5/24-05-24-19:57
 * @Description:com.wxlgroup.springboot.config
 * @Version:1.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");          //获取前端进行请求的请求头中的token
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401", "无token，请重新登录");
        }
        //获取token的userId
        String userId;
        try {
            userId=JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException e){
            throw new ServiceException("401","token验证失败");
        }
        //根据token解析出userId验证
        Response response1 = userService.queryUserById(Integer.parseInt(userId));
        if(response1.getResponseData()==null){
            throw new ServiceException("401","用户不存在，请重新登陆");
        }
        // 用户密码加签验证 token
        User user = (User) response1.getResponseData();
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("401", "token验证失败，请重新登录");
        }
        return true;
    }
}
